import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Config from '@/settings'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: Config.timeout // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const code = response.data.code
    if (code === 200) {
      return response.data
    } else {
      Message.error({
        message: response.data.msg,
        type: 'error',
        showClose: true,
        duration: Config.duration
      })
      return Promise.reject(new Error('fail'))
    }
  },
  error => {
    // 兼容blob下载出错json提示
    if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
      const reader = new FileReader()
      reader.readAsText(error.response.data, 'utf-8')
      reader.onload = function(e) {
        const errorMsg = JSON.parse(reader.result).message
        Notification.error({
          title: errorMsg,
          duration: 5000
        })
      }
    } else {
      let code = 0
      try {
        code = error.response.data.code
      } catch (e) {
        if (error.toString().indexOf('Error: timeout') !== -1) {
          Message.error({
            message: '网络请求超时',
            type: 'error',
            showClose: true,
            duration: Config.duration
          })
          return Promise.reject(error)
        }
      }
      console.log(code)
      if (code) {
        if (code === 401) {
          store.dispatch('LogOut').then(() => {
            // 用户登录界面提示
            // Cookies.set('point', 401)
            location.reload()
          })
        } else if (code === 403) {
          // router.push({ path: '/401' })
        } else {
          const errorMsg = error.response.data.message
          if (errorMsg !== undefined) {
            Message.error({
              message: errorMsg,
              type: 'error',
              showClose: true,
              duration: Config.duration
            })
          }
        }
      } else {
        Message.error({
          message: '接口请求失败',
          type: 'error',
          showClose: true,
          duration: Config.duration
        })
      }

      return Promise.reject(error)
    }
  }

)

export default service
